package com.itheima.controller;


import cn.hutool.core.util.IdUtil;
import com.itheima.common.AuthThreadLocal;
import com.itheima.common.JwtToken;
import com.itheima.common.R;

import com.itheima.pojo.vo.userVo.UserVo;
import com.itheima.service.UserService;
import com.itheima.service.impl.SendMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tcotk
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    private SendMessage sendMessage;
    @Resource
    private UserService userService;

    private String code;


    @PostMapping("/login")
    public R<Object> login(@RequestBody Map<String, String> map) {
        String phone = map.get("phone");
        String code = map.get("code");
        UserVo user = userService.selectByPhone(phone);


        if (code != null && code.equals(this.code)
                && user != null) {
            String userId = IdUtil.getSnowflakeNextIdStr();
            Map<String,Object>map1=new HashMap<>();
            map1.put("token",userId);
            String token = JwtToken.jwt(map1);
            user.setToken(token);
            return R.success(user);
        }


        return R.error("登入失败");
    }

    @PostMapping("/sendMsg")
    @ResponseBody

    public R<String> sendMsg(@RequestBody Map<String, String> map) {


        // UserVo user = userService.selectByPhone(map.get("phone"));
        // if (user == null) {
        //     Boolean add = userService.add(map);
        //     if (add) {
        //         this.code = sendMessage.msg(map.get("phone"));
        //         return R.success("当前用户不存在，系统帮你自动生产游客账号。");
        //     } else {
        //         return R.error("系统繁忙");
        //
        //     }
        //
        // }
        this.code = sendMessage.msg(map.get("phone"));
        log.info(code);
        return R.success("正在发送短信");




    }

    @PostMapping("/loginout")
    public R<String> loginOut() {
        AuthThreadLocal.remove();
        return R.success("登出成功");
    }


}
